package com.jsmy.marketing;


import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;

/**
 * @author leitao
 * @fileName pkg.shi.com.presenter
 * @date 2016/4/20
 * @update by     on
 */
public class MPresenter<T> implements MModelImpl.OnLoadDataListener{

    MView<T> mView;
    MModelImpl<T> mModel;
    private List<Observable<T>> observableList;
    private Observable<T> observable;

    public MPresenter(MView<T> mView) {
        this.mView = mView;
        this.mModel=new MModelImpl<>();
        this.observableList=new ArrayList<>();
    }

    public void loadData(Call call, String position){
        mView.showProgress();
        mModel.loadData(call,position,this);
    }
    public void loadData(Observable<T> observable, String position){
        this.observable=observable;
        this.observableList.add(observable);
        mView.showProgress();
        mModel.loadData(observable,position,this);
    }
    @Override
    public void onSuccess(Object object,String position) {
        mView.hideProgress();
        mView.refreshData(object,position);
        if (this.observable!=null){
            this.observable.unsubscribeOn(Schedulers.io());
        }
    }

    @Override
    public void onFailure(String msg) {
        mView.hideProgress();
        mView.showLoadFailMsg(msg);
    }
    public void cancle(){
        for (Observable<T> observable:observableList){
            observable.unsubscribeOn(Schedulers.io());
        }
    }
}
